package eiisan.security.service;

import eiisan.dao.domain.user.Permission;
import eiisan.dao.domain.user.Role;
import eiisan.dao.repository.user.PermissionRepository;
import eiisan.dao.repository.user.RoleRepository;
import eiisan.util.common.EmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class InitPermissionRoleService{

    @Autowired
    private PermissionRepository permissionRepository;

    @Transactional(rollbackFor = Exception.class)
    public List<Permission> saveNewPermissions(List<Permission> newPermissions){
        if (EmptyUtil.no(newPermissions)) {
            System.out.println("====================取出旧权限数据========================");
            List<Permission> repositoryAll = permissionRepository.findAll();
            System.out.println("原始权限条目数量:" + repositoryAll.size());

            Map<String, Set<Role>> prMap = repositoryAll.stream().collect(Collectors.toMap(Permission::getName,Permission::getRoles));

            System.out.println("====================新权限维持旧的role-permission关系========================");
            newPermissions.forEach(pl -> pl.setRoles(prMap.get(pl.getName())));
            System.out.println("====================删除旧权限数据========================");
            //1.删除旧数据
            permissionRepository.deleteAll();
            System.out.println("====================添加新权限数据========================");
            //2.保存新数据
            List<Permission> permissions = permissionRepository.saveAll(newPermissions);
            System.out.println("====================权限数据库添加完成========================");
            return permissions;
        }
        System.out.println("====================新权限数据为空========================");
        return null;

    }
}